var net = require('net'),
    sys = require('util');
var fs = require('fs');
var dir = require('path');
var cp = require('child_process');
//var nodes = require('multi-node');
var cert_path = 'cer/cer.pem';
//var keys_path = 'cer/key.pem';
var keys_path = 'cer/key.unencrypted.pem';//使用无密码是私钥
var APNS = require('./apns').createServer(cert_path, keys_path, 'gateway.push.apple.com');

function Client(stream) {
	this.stream = stream;
	this.buffer = "";
	this.ip = stream.remoteAddress;
	this.port = stream.remotePort;
	this.fd = stream.fd;
	this.stat = 0;
}

Client.prototype.log = function(error) {
	if(!error) return;
	var dateObj = new Date();
	var month = dateObj.getMonth() + 1;
	var log_file = Server.log + dateObj.getFullYear() + '-' + ((month < 10)?'0':'') + month + '.log';
	fs.open(log_file, 'a+', 0644, function (err, fd) {
		if(err) {
			console.log(err.message);
			return;
		}
		fs.writeSync(fd, error+"\n");
		fs.close(fd);
	});
}
Client.prototype.send = function(code, message) {
	if (this.stream.readyState !== "open" && this.stream.readyState !== "writeOnly") {
		this.log('send: '+code+' '+message);
		return false;
	}

	try {
		this.stream.write(''+code+' '+message+'\r\n');
	} catch (e) {
		// Ignore
		this.log('send1: '+code+' '+message);
	}
};

Client.prototype.close = function (e) {
	console.log("socket="+this.stream.fd+" ip="+this.stream.remoteAddress+"["+this.stream.remotePort+"] is close["+this.stream.server.connections+"]");
	this.stream.end();
	this.stream.destroy();
}

Client.prototype.connect = function (e) {
	console.log("socket="+this.stream.fd+" ip="+this.stream.remoteAddress+"["+this.stream.remotePort+"] is connect["+this.stream.server.connections+"]");
	if(e) {
		this.log(this.ip + " " + e);
	}
}

Client.prototype.timeout = function (e) {
	if(e) {
		this.log(this.ip + " " + e);
	}
	this.close();
}

Client.prototype.error = function (e) {
	if(e) {
		this.log(this.ip + " " + e);
	}
	this.close();
}

Client.prototype.end = function (e) {
	if(this.stat == 0) {
		console.log(this.buffer);
	}
	if(e) {
		this.log(this.ip + " " + e);
	}
	this.close();
}
Client.prototype.data = function (data) {
	//APNS.notify(device_id, { alert:"Hello", sound: "default", badge:1 });
	this.buffer += data;
	var apn = JSON.parse(data);
	if(apn.key == "IqXbB4M6") {
		for(var i in apn.data) {
			var token = apn.data[i]['device_token'];
			delete apn.data[i]['device_token'];
			var msg = apn.data[i];
			console.log(token,apn.data[i]);
			APNS.notify(token, msg);
		}
		this.send("200", "OK");
	}
	else {
		this.send("500", "ERR key error");
	}
	this.close();
}
Client.prototype.fork = function (buffer) {
	var n = cp.fork(__dirname + '/forward.js');
	n.on('message', function(m) {
		console.log('PARENT got message:', m);
	});
	n.send(buffer);
	setTimeout(function() {
		if(n.pid > 0) {
			// 记录超时的进程
			console.log("n=",n);
			n.kill();
		}
	}, 60000);
}

// 服务配置
function Server() {
}
Server.hostname = "levsion.com";
Server.port = 22195;
//Server.address = "127.0.0.1";
Server.address = "50.116.4.160";
Server.path = "/home/node/";
Server.log = "/tmp/node/";

var server = net.createServer(function (stream) {
	var client = new Client(stream);
	// 设置编码
	stream.setEncoding('utf8');
	// 设置超时60秒
	stream.setTimeout(1000*60);
	stream.setNoDelay(true);
	stream.on('connect', function (e) {
		client.connect();
	});
	stream.on('data', function (data) {
		client.data(data);
	});
	stream.on('timeout', function (e) {
		client.timeout();
	});
	stream.on('end', function (e) {
		client.end();
	});
	stream.on('error', function (e) {
		client.error(e);
	});
});

server.listen(Server.port, Server.address);
// 启动多个进程
//nodes.listen({port: Server.port, host: Server.address,nodes: 2}, server);
